<template>
  <div>
    <Select
      v-if="onlyProvince"
      v-model="value"
      clearable
      @on-change="onSelectAreaList"
      >
      <Option v-for="item in addressList"
        :value="item.id" :key="item.id">{{ item.value }}
      </Option>
    </Select>
    <Cascader 
      :data="cascaderList"
      :change-on-select='isChangeOnSelect'
      :load-data="loadData"
      v-model="value"
      @on-change="onSelectArea"
      placeholder="请选择地区"
      v-else 
    ></Cascader>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      cascaderList: []
    }
  },
  props: {
    value: {
      type: Array,
      default:() => []
    },
    onlyProvince: {
      type: Boolean,
      default: false,
    },
    isChangeOnSelect: {
      type: Boolean,
      default: false
    },
    isGetAddressTree: {
      type: Boolean,
      default: true
    }
  },
  mounted() {
    if (this.onlyProvince) {
      this.$store.dispatch('ajaxAddress', { type: 'province' })
    } else {
      if (this.isGetAddressTree) {
        this.getArea({}).then(res => {
          this.cascaderList = res
        })
      }
    }
  },
  methods: {
    getArea(params) {
      return new Promise((resolve, reject) => {
        this.$ajaxGet('/tiger/area/list_by_parentId',  params).then(res => {
          resolve(res.map(item => {
            item.label = item.name
            item.value = item.id
            item.children = []
            if (item.treeLevel != 3) {
              item.loading = false
            }
            if (item.children == 3) {
              delete item.children
            }
            return item
          }))
        })
      })
    },
    loadData (item, callback) {
      item.loading = true;
      this.getArea({parentId: item.value}).then(res => {
        item.loading = false
        if (!res.length) {
          delete item.loading
        } else {
          item.children = res
        }
        callback();
      })
    },
    onSelectArea(val, selectedData){
      this.$emit('input', val, selectedData)
    },
    onSelectAreaList(val) { 
      this.$emit('input', val)
    },
    updateArea(arr) {
      this.currValue = arr
    }
  },
  computed: {
    ...mapGetters(['addressList'])
  },
}
</script>

